<template>
	<view>
		<!-- <u-navbar title="采购" @rightClick="rightClick" :autoBack="false" :bgColor="bgColor" :titleStyle="titleStyle"
			:fixed="true">
			<view slot="left"></view>
			<view slot="right" :style="titleStyle">增加</view>
		</u-navbar>
		<u-gap height="44"></u-gap> -->
		<u-sticky bgColor="#fff">
			<u-tabs :list="tabs" @click="tabClick" :activeStyle="activeStyle" lineColor="#675f91" :current="current">
				<view slot="right" class="text-primary" style="padding-right: 10px;" v-if="isPurchaser">
					<!-- <picker @change="bindAddPicker" value="0" :range="add_picker_arr" range-key="label">
						<u-button type="primary" size="small" text="增加"></u-button>
					</picker> -->
					<u-button type="primary" size="small" text="增加" @tap="rightClick"></u-button>
				</view>
			</u-tabs>
			<!-- <u-button type="primary" size="small" text="增加" @tap="rightClick"></u-button> -->
			<u-line></u-line>
			<view class="blank20"></view>
			<view class="wrapper flex">
				<view class="text-gray mr15">
					筛选：
				</view>
				<!-- <view class="flex-1 mr15">
					<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
						<view class="flex">
							<view class="flex-1 text-primary font-bold">
								<view>{{date || '全部日期'}}</view>
							</view>
							<u-icon name="arrow-right" color="#999999" size="14"></u-icon>
						</view>
					</picker>
				</view> -->
				<!-- <view class="" @click="clearDate">
					<u-icon name="close-circle"></u-icon>
				</view> -->
				<view class="flex-1" v-if="date_arr.length>0">
					<picker @change="bindDateChange" :value="date_index" :range="date_arr" range-key="label">
						<view class="flex">
							<view class="flex-1 text-primary font-bold">
								<view>{{date_arr[date_index].label}}</view>
							</view>
							<u-icon name="arrow-right" color="#999999" size="14"></u-icon>
						</view>
					</picker>
				</view>
				<view class="ml15 mr15"></view>
				<view class="flex-1" v-if="supplier_arr.length>0">
					<picker @change="bindSupplierChange" :value="supplier_index" :range="supplier_arr" range-key="label">
						<view class="flex">
							<view class="flex-1 text-primary font-bold">
								<view>{{supplier_arr[supplier_index].label}}</view>
							</view>
							<u-icon name="arrow-right" color="#999999" size="14"></u-icon>
						</view>
					</picker>
				</view>
			</view>
			<view class="blank20"></view>
			<u-line></u-line>
			<!-- <view class="blank20"></view>
			<view class="text-gray font-24 wrapper">
				<view class="flex">
					<view class="flex-1">
						下单日期
					</view>
					<view class="" style="width: 20%;">
						条数
					</view>
					<view class="" style="width: 15%;">
						花费
					</view>
					<view class="text-center" style="width: 60px">
						操作
					</view>
				</view>
			</view>
			<view class="blank20"></view>
			<u-line></u-line> -->
		</u-sticky>
		<view class="">
			<view class="blank20"></view>

			<template v-for="(v,i) in list">
				<chefItem :detail="v" v-if="current == 0"></chefItem>
				<purchaserItem :detail="v" :is_org_purchaser="is_org_purchaser" v-if="current == 1"></purchaserItem>
			</template>

			<nodata v-if="loadingStatus == 'end' && list.length == 0"></nodata>
			<!-- <u-loadmore :status="status" :loading-text="loadingText" :loadmore-text="loadmoreText" :nomore-text="nomoreText" /> -->
			<view class="blank30"></view>

			<u-modal :show="modalShow" title="提示" :content='modalContent' :showCancelButton="true" confirmColor="#675f91"
				@confirm="modalConfirm" @cancel="modalCancel"></u-modal>
		</view>
	</view>
</template>

<script>
	import chefItem from './components/chef-item.vue';
	import purchaserItem from './components/purchaser-item.vue';
	import nodata from '@/components/nodata.vue';
	import {
		po_pr_record,
		get_user_session_id,
		purchase_request_delete,
		org_pr_list
	} from '@/common/api.js';
	export default {
		components: {
			chefItem,
			purchaserItem,
			nodata
		},
		data() {
			return {
				add_picker_arr: [{
						label: '从食材库中选择',
						id: 'food'
					},
					{
						label: '根据供应商的报价单选择',
						id: 'supplier'
					},
					{
						label: '市场选择',
						id: 'market'
					},
				],
				current: 0,
				activeStyle: {
					color: '#675f91'
				},
				tabs: [{
						name: '已下单'
					},
					{
						name: '待审批'
					},
				],
				date: '',
				role: this.$store.getters.get_role,
				isChef: true,
				isPurchaser: false,
				is_org_purchaser: false,
				// isPurchaser: this.$store.getters.get_role.inclueds('采购'),
				modalContent: '',
				modalShow: false,

				titleStyle: {
					color: '#ffffff'
				},
				bgColor: '#675f91',
				statusObj: {
					's0_draft': '草稿',
					's1_handin': '已提交',
					's2_accepted': '已批准',
					's3_rejected': '驳回',
					's4_closed': '已下单',
				},
				list: [],
				page: 0,
				status: 'nomore',
				loadingText: '努力加载中',
				loadmoreText: '轻轻上拉',
				nomoreText: '没有了',
				delId: '',
				// supplier_arr:[],
				supplier_index: 0,
				date_index: 0,
				org_po_list: [],
				org_pr_list: [],
				loadingStatus: '',
			}
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			},
			supplier_arr() {
				let arr = [{
					label: '全部供应商'
				}];
				let list = this.current == 0 ? this.org_po_list : this.org_pr_list;
				if (list.length == 0) {
					return arr;
				}
				list.forEach(v => {
					v.child.forEach(d => {
						if (!arr.find(a => a.label == d.supplier_id[1])) {
							arr.push({
								label: d.supplier_id[1]
							})
						}
					})
				})
				return arr;
			},
			date_arr() {
				let arr = [{
					label: '全部日期'
				}];
				let list = this.current == 0 ? this.org_po_list : this.org_pr_list;
				if (list.length == 0) {
					return arr;
				}
				list.forEach(v => {
					if (!arr.find(a => a.label == v.date)) {
						arr.push({
							label: v.date
						})
					}
				})
				return arr;
			}
		},
		methods: {
			bindSupplierChange(e) {
				let index = e.detail.value;
				this.supplier_index = index;
				this.updataList();
			},
			bindDateChange(e) {
				let index = e.detail.value;
				this.date_index = index;
				this.updataList();
			},
			updataList() {
				let list = JSON.parse(JSON.stringify(this.current == 0 ? this.org_po_list : this.org_pr_list));
				if (this.date_index != 0) {
					let date = this.date_arr[this.date_index].label;
					list = list.filter(v => v.date == date);
				}
				if (this.supplier_index != 0) {
					let supplier = this.supplier_arr[this.supplier_index].label;
					list.forEach(v => {
						v.child = v.child.filter(d => d.supplier_id[1] == supplier)
					})
					list = list.filter(v => v.child.length > 0);
				}
				this.list = list;
			},
			bindAddPicker(e) {
				let index = e.detail.value;
				if (this.add_picker_arr[index].id == 'food') {
					this.nav('/food/food');
				} else {
					uni.$u.toast('开发中');
				}
			},
			tabClick(e) {
				this.current = e.index;
				this.supplier_index = 0;
				this.date_index = 0;
				this.list = this.current == 0 ? this.org_po_list : this.org_pr_list;
				// console.log(this.list);
				// this.$forceUpdate();
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			// bindDateChange: function(e) {
			// 	this.date = e.detail.value;
			// },
			// clearDate() {
			// 	this.date = '';
			// },
			modalConfirm() {
				this.modalShow = false;
				this.purchase_request_delete();
			},
			modalCancel() {
				this.modalShow = false;
			},
			rightClick() {
				this.nav('/food/food');
			},
			del(v) {
				this.modalContent = '确认删除该采购申请？删除后无法恢复。';
				this.modalShow = true;
				this.delId = v.id;
			},
			purchase_request_delete() {
				uni.showLoading({
					title: '加载中'
				});
				purchase_request_delete({
					pr_id: this.delId
				}).then((res) => {
					this.list = this.list.filter(v => v.id != this.delId);
					uni.$u.toast('删除成功');
				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			editPurchase(v) {
				let status = v['状态'];
				if (status == 's0_draft') {
					this.nav('/purchaseDetail/purchaseDraft?id=' + v.id);
				} else {
					this.nav('/purchaseDetail/purchaseDetail?id=' + v.id);
				}
			},
			getData() {
				uni.showLoading({
					title: '加载中'
				});
				this.supplier_index = 0;
				this.date_index = 0;
				this.loadingStatus = 'loading';
				po_pr_record().then((res) => {
					// this.list = res.result;
					let {
						org_po_detail,
						org_po_record,
						org_pr_detail,
						org_pr_record
					} = res.result;
					uni.setStorage({
						key: 'po_pr_record',
						data: res.result,
						success: function() {}
					});
					
					let listObj = {};
					let org_pr_obj = {};
					let org_po_obj = {};
					org_pr_record.forEach((v, i) => {
						// console.log(i);
						// console.log(v.place_time);
						// console.log(this.momentTZ(v.place_time));
						let org_pr_detail_item_arr = org_pr_detail.filter(item => item.org_pr_pending_id[0] == v.id);
						if (org_pr_detail_item_arr.length == 0) {
							return;
						}
						v.place_time = this.momentTZ(v.place_time);
						!org_pr_obj[v.date] && (org_pr_obj[v.date] = []);
						let _length = org_pr_obj[v.date].push({
							...v,
							_key: 'org_pr_record',
							child: [],
							_place_time: new Date(v.place_time).getTime()
						});
						org_pr_detail_item_arr.forEach(d => {
							org_pr_obj[v.date][_length - 1].child.push(d)
						})
					})
					org_po_record.forEach(v => {
						v.place_time = this.momentTZ(v.place_time);
						!org_po_obj[v.date] && (org_po_obj[v.date] = []);
						let _length = org_po_obj[v.date].push({
							...v,
							_key: 'org_po_record',
							child: [],
							_place_time: new Date(v.place_time).getTime(),
						});
						org_po_detail.forEach(d => {
							if (d.org_po_id[0] == v.id) {
								org_po_obj[v.date][_length - 1].child.push(d)
							}
						})
					})

					let list = [];
					let org_pr_list = [];
					let org_po_list = [];

					for (let date in org_pr_obj) {
						let child = org_pr_obj[date].sort((a, b) => b._place_time - a._place_time)
						org_pr_list.push({
							date: date,
							child: child
						})
					}
					for (let date in org_po_obj) {
						let child = org_po_obj[date].sort((a, b) => b._place_time - a._place_time)
						org_po_list.push({
							date: date,
							child: child
						})
					}
					// console.log(list);
					this.org_pr_list = org_pr_list;
					this.org_po_list = org_po_list;
					this.list = this.current == 0 ? org_po_list : org_pr_list;
				}).catch(() => {
					uni.hideLoading();
				}).finally(() => {
					this.loadingStatus = 'end';
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			}
		},
		onLoad() {
			// this.getData();
			try {
				this.role = this.$store.getters.get_role;
				console.log(this.role);
				this.isPurchaser = this.role['采购模块'].is_purchaser;
				this.is_org_purchaser = this.role['采购模块'].is_org_purchaser;
				// this.isPurchaser = true;
				this.isChef = true;
				this.getData();
			} catch (e) {
				uni.reLaunch({
					url: '/pages/login/login'
				});
			}
		},
		onShow() {
			uni.$off('refresh_index');
			uni.$once('refresh_index',()=>{
				this.getData();
			})
		},
		onReady() {

		},
		onPullDownRefresh() {
			this.getData();
		}
	}
</script>

<style lang="scss" scoped>
	@import './purchase.scss';

	/deep/.item {
		padding: 20upx 30upx;
	}

	/deep/.food-box {
		margin: 0 20upx 0 20upx;
		background-color: #ededed;
		padding: 0;
	}

	/deep/.food-box .item {
		padding: 10upx 10upx;
	}

	/deep/.active.time-item-box {
		position: relative;
		// border: 1px solid #675f91;
		// border-top: 1px solid #675f91;
		border-bottom: 1px solid #675f91;
	}

	/deep/.time-box::before {
		// position: absolute;
		// content: ' ';
		// width: 2px;
		// height: 100%;
		// top: 0;
		// bottom: 0;
		// left: 2upx;
		// background-color: #675f91;
	}

	/deep/ .icon-btn {
		padding: 3px;
		border: 1px solid #d9d9d9;
		border-radius: 50%;
	}

	/deep/ .icon-btn.active {
		background-color: #675f91;
		border-color: #675f91;
	}
</style>